/**
 * 描述：业务相关
 * 作者：zhaohaibo
 * 日期：2018-07-21
 * 版本：0.0.1
 **/
(function(E, KIT, RES) {

  RES.ARR_PAY = [{text: "已退款", value: 2}, {text: "缴费成功", value: 1}, {text: "缴费中", value: 0}];
  RES.ARR_FORM_TYPE = [{text: "普通表单", value: 1}, {text: "生命周期表单", value: 0}];
  RES.ARR_STATUS_TYPE = [{text: "启用", value: 1}, {text: "禁用", value: 0}];

  KIT.loadAdminResourceSync = function(url) {
    var __msg = "请注意：\n项目正运行在【开发者模式】中，请在正式部署前，将\n“/net/yxsoft/common/resource/Res.java”中的\n“DEV_MODE”设置为 false。";

    if(!window.top.rapid || (!window.top.rapid.res.__RESOURCE_LOADED__ && !rapid.res.__RESOURCE_LOADED__)) {
      rapid.post({
        async: false,
        url: url,
        success: function(data) {
          if(rapid.isEmpty(data)) {
            window.top.location.href = RES.URL_ROOT + "/reLogin";
            return;
          }

          var __res = {};

          __res.DEV_MODE = rapid.nvl(data.DEV_MODE, false);

          __res.PROJECT_NAME = rapid.nvl(data.PROJECT_NAME, "系统");

          __res.ENUM_USER_TYPES = rapid.EnumList(data.USER_TYPES);

          //加载数据字典学历
          __res.DDDDSS = data.RECORD_LIST;

          //加载公司名称
          __res.COMPANY = data.ORG_LIST;

          //加载职位
          __res.JOB = data.JOB_LIST;

          //加载人员信息
          __res.CONTACT = data.CONTACT_LIST;

          //加载关联表单信息
          __res.FORMNAME = data.FORM_LIST;

          //加载附件类型信息
          __res.FILETYPE = data.FILE_TYPE_LIST;

          //加载工作流状态信息
            __res.STASK_STATUS=data.STASK_LIST;

          __res.ENUM_SEX = rapid.EnumList(data.sex);
          //是否
          __res.ENUM_GZY = data.IS_GZY;
          //是否为管理员
          __res.ENUM_ADMIN = data.IS_ADMIN;

          // 顶级组 编号
          __res.GROUP_ROOT_CODE = data.GROUP_ROOT_CODE;
          // 顶级组 名称
          __res.GROUP_ROOT_NAME = data.GROUP_ROOT_NAME;
          // 顶级组 ID
          __res.GROUP_ROOT_ID = data.GROUP_ROOT_ID;

          __res.USER_ID = data.USER_ID;
          __res.USER_NAME = data.USER_NAME;
          __res.USER_TYPE = data.USER_TYPE;
          __res.USER_PHONE = data.USER_PHONE;

          // 当前登录用户所在的组
          __res.USER_GROUPS = data.USER_GROUPS;
          // 当前登录用户所在的组的id
          __res.USER_GROUP_IDS = data.USER_GROUP_IDS;
          // 当前登录用户所在的组的名称
          __res.USER_GROUP_NAMES = data.USER_GROUP_NAMES;
          // 当前登录用户的组 是否包含顶级组
          __res.USER_HAS_ROOT_GROUP = data.USER_HAS_ROOT_GROUP;

          // --------------------- 附加信息 ---------------------

          rapid.extend(rapid.res, __res);
          rapid.res.__RESOURCE_LOADED__ = true;

          if(window.top != window && window.top.rapid) {
            window.top.rapid.res = __res;
            window.top.rapid.res.__RESOURCE_LOADED__ = true;
          }

          if(__res.DEV_MODE) {
            alert(__msg);
          }
        }
      });
    } else {
      if(window.top.rapid) {
        rapid.extend(rapid.res, window.top.rapid.res);
        rapid.res.__RESOURCE_LOADED__ = true;
      }
    }

    if(rapid.res.DEV_MODE) {
      console.log(__msg);
    }
  };

  //region 视频通话相关

  KIT.push = function(options) {

    // 页面处理，显示视频流页面
    $("#video-section").show();
    $("#remote-video-wrap").show();

    initRTC({
      "userId": options.userId,
      "userSig": options.userSign,
      "sdkappid": options.sdkAppId,
      "accountType": 1, // 随便传一个值，现在没有啥用处
      "roomid": options.roomId,
      "privateMapKey":options.privateMapKey
    });
  };
  KIT.quitRTC = function() {
    RTC.quit();
    $("#video-section").hide();
    $("#input-container").show();
    $("#remote-video-wrap").html("");
  };

  KIT.stopRTC = function() {
    RTC.stopRTC(0, function (info) {
      // console.debug(info)
    }, function (info) {
      // console.debug(info)
    });
  };

  KIT.startRTC = function() {
    RTC.startRTC(0, function (info) {
      console.debug('success', info)
    }, function (info) {
      console.debug('failed', info)
    });
  };

  var initRTC = function (opts) {
    window.RTC = new WebRTCAPI({
      userId: opts.userId,
      userSig: opts.userSig,
      sdkAppId: opts.sdkappid,
      accountType: opts.accountType
    }, function () {
      RTC.enterRoom({
        roomid: opts.roomid * 1,
        privateMapKey: opts.privateMapKey,
        role: "user",
      }, function (info) {
        console.warn("init succ", info)
        gotStream({
          audio:true,
          video:true
        },function(stream){
          RTC.startRTC({
            stream: stream,
            role: 'user'
          });
        })
      }, function (error) {
        console.error("init error", error)
      });
    }, function (error) {
      // console.warn("init error", error)
    });

    // 远端流新增/更新
    RTC.on("onRemoteStreamUpdate", onRemoteStreamUpdate)
    // 本地流新增
    RTC.on("onLocalStreamAdd", onLocalStreamAdd)
    // 远端流断开
    RTC.on("onRemoteStreamRemove", onRemoteStreamRemove)
    // 重复登录被T
    RTC.on("onKickout", onKickout)
    // 服务器超时
    RTC.on("onRelayTimeout", onRelayTimeout)

    RTC.on("onErrorNotify", function (info) {
      console.error(info)
      if (info.errorCode === RTC.getErrorCode().GET_LOCAL_CANDIDATE_FAILED) {
        // alert( info.errorMsg )
      }
    });
    RTC.on("onStreamNotify", function (info) {
      // console.warn('onStreamNotify', info)
    });
    RTC.on("onWebSocketNotify", function (info) {
      // console.warn('onWebSocketNotify', info)
    });
    RTC.on("onUserDefinedWebRTCEventNotice", function (info) {
      // console.error( 'onUserDefinedWebRTCEventNotice',info )
    });
  };

  var onKickout = function() {
    alert("on kick out!");
  };

  var onRelayTimeout = function (msg) {
    rapid.info("onRelayTimeout!" + (msg ? JSON.stringify(msg) : ""));
  };

  var createVideoElement = function (id, isLocal) {
    var videoDiv = document.createElement("div");
    videoDiv.innerHTML = '<div class="r-p r-al-c">' + (isLocal ? '公证员' : '公证申请人') + '</div><video id="' + id + '" autoplay ' + (isLocal ? 'muted' : '') + ' playsinline ></video>';
    document.querySelector("#remote-video-wrap").appendChild(videoDiv);
    return document.getElementById(id);
  };

  var onLocalStreamAdd = function (info) {
    if (info.stream && info.stream.active === true) {
      var id = "local";
      var video = document.getElementById(id);
      if (!video) {
        createVideoElement(id, true);
      }
      var video = document.getElementById(id)
      video.srcObject = info.stream;
      video.muted = true;
      video.autoplay = true;
      video.playsinline = true;
    }
  };

  var onRemoteStreamUpdate = function (info) {

    if (info.stream && info.stream.active === true) {
      var id = info.videoId;
      var video = document.getElementById(id);
      if (!video) {
        video = createVideoElement(id);
      }
      video.srcObject = info.stream;

    } else {
      console.log('欢迎用户' + info.userId + '加入房间');
    }
  };

  var onRemoteStreamRemove = function(info) {
    console.log(info.userId + ' 断开了连接');
    var videoNode = document.getElementById(info.videoId);
    if (videoNode) {
      videoNode.srcObject = null;
      document.getElementById(info.videoId).parentElement.removeChild(videoNode);
    }
  };

  var onWebSocketClose = function() {
    RTC.quit();
  };

  var gotStream = function( opt ,succ){
    RTC.getLocalStream({
      video:true,
      audio:true,
      videoDevice: {
        facingMode:{
          ideal:'user'  // 'environment' 表示后置摄像头  | 'user'表示前置摄像头
        }
      },
      // 如需指定分辨率，可以在attributes中增加对width和height的约束
      // 否则将获取摄像头的默认分辨率
      // 更多配置项 请参考 接口API
      // https://cloud.tencent.com/document/product/647/17251#webrtcapi.getlocalstream
      attributes:{
          width:360,
          height:480
      }
    },function(info){
      var stream = info.stream;
      succ ( stream )
    });
  };

  var audience = function() {
    login(true);
  };

  var stopWs = function() {
    RTC.global.websocket.close();
  };

  var mediaSource = new MediaSource();
  mediaSource.addEventListener('sourceopen', handleSourceOpen, false);
  var mediaRecorder;
  var recordedBlobs;
  var sourceBuffer;

  KIT.startScor = function(){

    window.gumVideo = document.querySelector('video#local');

    // window.isSecureContext could be used for Chrome
    var isSecureOrigin = location.protocol === 'https:' || location.hostname === 'localhost';
    if (!isSecureOrigin) {
      alert('getUserMedia() must be run from a secure origin: HTTPS or localhost.' + '\n\nChanging protocol to HTTPS');
      location.protocol = 'HTTPS';
    }

    var constraints = {
      audio: true,
      video: {
        width:360,//视频宽度
        height:480,//视频高度
        frameRate:60,//每秒60帧
      }
    };

    navigator.mediaDevices.getUserMedia(constraints).
    then(handleSuccess).catch(handleError);
  };

  var handleSuccess = function(stream) {
    console.log('getUserMedia() got stream: ', stream);
    window.stream = stream;
    //gumVideo.srcObject = stream;

    startRecording();
  };

  var handleError = function(error) {
    console.log('navigator.getUserMedia error: ', error);
  };

  var startRecording = function(){

    recordedBlobs = [];
    var options = {mimeType: 'video/webm;codecs=h264'};
    try {
      mediaRecorder = new MediaRecorder(window.stream, options);
    } catch (e) {
      console.error('Exception while creating MediaRecorder: ' + e);
      return;
    }
    console.log('Created MediaRecorder', mediaRecorder, 'with options', options);

    mediaRecorder.onstop = handleStop;
    mediaRecorder.ondataavailable = handleDataAvailable;
    mediaRecorder.start(10); // collect 10ms of data
    console.log('MediaRecorder started', mediaRecorder);
  };

  KIT.stopRecording = function(){

    mediaRecorder.stop();
    console.log('Recorded Blobs: ', recordedBlobs);

    var blob = new Blob(recordedBlobs, {type: 'video/mp4'});
    var formData = new FormData();
    formData.append('video', blob);

    $.ajax({
      url: "/sysadmin/api/upload",
      type: 'POST',
      cache: false,
      data: formData,
      processData: false,
      contentType: false,
      dataType:"json",
      success : function(data) {

      }
    });
  };

  var handleDataAvailable = function(event) {
    if (event.data && event.data.size > 0) {
      recordedBlobs.push(event.data);
    }
  };

  var handleSourceOpen = function(event) {
    console.log('MediaSource opened');
    sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"');
    console.log('Source buffer: ', sourceBuffer);
  };

  var handleStop = function(event) {
    console.log('Recorder stopped: ', event);
  };

  //endregion

  /**
   * websocket命令封装
   * @param name
   * @param data
   * @returns {*}
   */
  KIT.cmd = function(name, data) {
    if(rapid.isJson(data)) {
      return name + rapid.parseString(data);
    }

    return name + data;
  };

})(rapid.html.Element, rapid.kit, rapid.res);